<template>
  <div class="app-container">



    <!-- 表格 -->
    <dy-table
      border
      align="center"
      layout="total, sizes, prev, pager, next, jumper"
      :column="tbaleColumns"
      :data="tableData"
      :pager-count="5"

      background
      :height="700"
      :total="pagination.total"
      :current-page.sync="pagination.currentPage"
      :page-size="pagination.pageSize"
      :page-sizes="pagination.pageSizes"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
      >
    </dy-table>

    <!-- 编辑框 -->
    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
      <el-form
        ref="dataForm"
        :model="dataForm"
        label-width="100px"
        size="small"
        style="padding-right: 40px"
        :rules="FormRules"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="名称-英文" prop="name_en">
          <el-input v-model="dataForm.name_en" />
        </el-form-item>
        <el-form-item label="简介" prop="info">
          <el-input type="textarea" v-model="dataForm.info" />
        </el-form-item>
        <el-form-item label="简介-英文" prop="info_en">
          <el-input type="textarea" v-model="dataForm.info_en" />

        </el-form-item>
        <el-form-item label="座右铭" prop="mottom">
          <el-input type="textarea" v-model="dataForm.mottom" />
        </el-form-item>
        <el-form-item label="座右铭-英文" prop="mottom_en">
          <el-input type="textarea" v-model="dataForm.mottom_en" />

        </el-form-item>
  
        <el-form-item label="投票数" prop="sort">
          <el-input v-model="dataForm.sort" />
        </el-form-item>
        <el-form-item label="选举人图片" prop="pic_url">
          <el-col :span="12">       
            <el-image v-if="dataForm.pic_url" class="ya-img-form" :src="dataForm.pic_url" fit="contain" :preview-src-list="[dataForm.pic_url]" title="点击看大图">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
            <el-image v-else class="ya-img-form" fit="contain" title="">
              <div slot="error" class="image-slot" />
            </el-image>    
           </el-col>
      
          <el-col :span="12">
            <el-button size="mini" @click="fileUpload()">上传图片 </el-button>
            <el-button size="mini" >删除</el-button>
            <p>图片小于 200 KB，jpg、png格式。</p>
          </el-col>
        </el-form-item>
     
        <el-form-item label="收益率" prop="link">
          <el-input type="textarea" v-model="dataForm.link" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="small"
          icon="el-icon-refresh-right"
          >取 消</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="saveOrUpdate()"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
        <!-- 文件管理 -->
      <el-dialog title="上传图片" :visible.sync="fileDialog" width="80%" top="1vh" :close-on-click-modal="false" :close-on-press-escape="false">
      <file-manage file-type="image" @fileCancel="fileCancel" @fileSubmit="fileSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import DyTable from '@/components/lb-table/lb-table.vue';
import screenHeight from '@/utils/screen-height'
import {list,add,edit,dele,info} from "@/api/school/homeMenu.js";
import FileManage from '@/components/FileManage'
export default {
  components: {
    DyTable,
    FileManage
  },
  data() {
    return {
      //屏幕高度
      height:800,
      fileDialog: false,
      //时间选择器获取数据
      createTimes: [],
      //获取列表请求参数
      params: {
        page: 1,
        pageSize: 15,
        searchObj: {
          keyword: '',
        },
      },
      //table列
      tbaleColumns: [
        {
          label: '排名',
          width: 100,
          type: 'index',
        },
        {
          prop: 'name',
          label: '名称',
        },
        {
          prop: 'name_en',
          label: '名称-英文',
        },
        {
          prop: 'mottom',
          label: '座右铭',
        },
        {
          prop: 'mottom_en',
          label: '座右铭-英文',
        },
        {
          prop:"pic_url",
          label:"选举人图片",
          render: (h, scope) => {
            if(scope.row.pic_url){
                return (
                  <el-image  class="ya-img-form" fit="contain"  
                    src={scope.row.pic_url} 
                    title="点击看大图" 
                    preview-src-list={[scope.row.pic_url]}>
                  </el-image>
              )
            }else{
                return (
                  <div></div>
                )
            }
          
          },
        },
        {
          prop:"link",
          label:"收益率"
        },
        {
          prop:"sort",
          label:"投票数"
        },
        {
          prop:"info",
          label:"简介"
        },
        // 英文简介
        {
          prop: 'info_en',
          label: '简介-英文',
        },
        {
          label: '操作',
          render: (h, scope) => {
            return (
              <div>
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  onClick={() => {
                    this.edit(scope.row.id)
                  }}
                  title="修改"
                />
          
               
              </div>
            )
          },
        },
      ],
      //table数据
      tableData: [],
      //table分页
      pagination: {
        pageSize: 6, //每页条数
        currentPage: 1, //当前页
        total: 100, // 总数
        pageSizes: [6, 20, 30, 40, 50, 100], //可选每页条数
      },
      //数据表单
      dataForm: {},
      //tp专用
      formKeys: ['id','pic', 'link', 'name','sort','pic_url',
      'info','name_en','info_en','mottom','mottom_en'],
      //表单验证器
      FormRules: {
        name: [{ required: true, trigger: 'blur' }],
      },
      //加载控制
      loading: false,
      //编辑弹窗控制器
      dialogVisible: false,
      // 验证规则
      validatePassword,
      //时间选择器获取数据
      createTimes: [],
    }
  },
  created() {
    //获取屏幕高度
    this.height= screenHeight() -100;
    console.log(this.height);
    //调用列表方法
    this.fetchData()
  },
  methods: {
    switchButton(str){
      console.log(str);
   

    },
    //选择文件
    fileSubmit(filelist) {
      console.log(filelist);
      this.fileDialog = false
      if (filelist) {
        this.dataForm.pic = filelist[0]['file_id']
        this.dataForm.pic_url = filelist[0]['file_url']
      }
    },
      // 上传logo
    fileUpload() {
      this.fileDialog = true
    },
    fileCancel() {
      this.fileDialog = false
    },
    // 获取数据
    fetchData() {
      // 真实案例，使用api调用
        this.params.pageSize = this.pagination.pageSize;
        this.params.page = this.pagination.currentPage;
      //时间范围
        if(this.createTimes && this.createTimes.length==2){
            this.params.searchObj.createTimeBegin = this.createTimes[0],
            this.params.searchObj.createTimeEnd = this.createTimes[1]
         }else{
          this.params.searchObj.createTimeBegin ='',
            this.params.searchObj.createTimeEnd =''
         }

        list(this.params).then((res) => {
            res =res.data;
            this.tableData = res.data;
            this.pagination.total = res.total;
            this.pagination.currentPage = res.current_page;
          });
    },
    // 新增或者编辑
    saveOrUpdate() {
      //表单验证
      this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            console.log(this.dataForm);
            //判断是新增还是编辑
            if(!this.dataForm.id) {
                this.save()
              } else {

                this.update()
              }
          } else {
            return false;
          }
        });
    },
    //新增
    save() {
      add(this.dataForm)
        .then(response => {
          //提示
          this.$message.success('操作成功')
          //关闭弹框
          this.dialogVisible = false
          //刷新
          this.fetchData()
        })
    },
    //更新
    update() {
      edit(this.dataForm)
        .then(response => {
          //提示
          this.$message.success('操作成功')
          //关闭弹框
          this.dialogVisible = false
          //刷新
          this.fetchData()
        })
    },
    //添加按钮
    add() {
      this.dialogVisible = true
      this.dataForm = {}
    },
    // 编辑按钮
    edit(id) {
      //弹出框
      this.dialogVisible = true
      //获取数据给From
      //调用接口查询
      info(id)
        .then(response => {
        this.dataForm = _.pick(response.data,this.formKeys);
       })
    },
    //删除
    removeDataById(id) {
      this.$confirm('删除!, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        //调用方法删除
        

        dele([id] )
          .then(response => {
            //提示
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //刷新
            this.fetchData()
        })
      })
    },
    // 重置查询表单
    resetData() {
      this.params.searchObj.keyword = ''

      this.createTimes = []
      this.fetchData()
    },

    // pageSize 改变时会触发
    handleSizeChange(val) {
      this.pagination.currentPage = 1
      this.pagination.pageSize = val
      this.fetchData()
    },
    // currentPage 改变时会触发
    handleCurrentChange() {
      this.fetchData()
    },
  },
}
//验证规则
const validatePassword = (rule, value, callback) => {
  if (!validUsername(value)) {
    callback(new Error('Please enter the correct user name'))
  } else {
    callback()
  }
}
</script>

<style></style>
